﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace LocalTrackerData
{
    class DataSetHelper
    {
        public DataSet _ds;
        public DataSetHelper(ref DataSet dataSet)
        {
            _ds = dataSet;
        }

        public DataSetHelper()
        {
            _ds = null;
        }

        private bool ColumnEqual(object a, object b)
        {
            // Compares two values to see if they are equal. Also compares DBNULL.Value.
            // Note: If your DataTable contains object fields, then you must extend this
            // function to handle them in a meaningful way if you intend to group on them.
            if (a == DBNull.Value && b == DBNull.Value) //  both are DBNull.Value
                return true;
            if (a == DBNull.Value || b == DBNull.Value) //  only one is DBNull.Value
                return false;
            return (a.Equals(b));  // value type standard comparison
        }

        public DataTable SelectDistinct(string tableName, DataTable sourceTable, string fieldName)
        {
            DataTable dt = new DataTable(tableName);
            dt.Columns.Add(fieldName, sourceTable.Columns[fieldName].DataType);

            object LastValue = null;
            foreach (DataRow dr in sourceTable.Select("", fieldName))
            {
                if (LastValue == null || !(ColumnEqual(LastValue, dr[fieldName])))
                {
                    LastValue = dr[fieldName];
                    dt.Rows.Add(new object[] { LastValue });
                }
            }
            if (_ds != null)
                _ds.Tables.Add(dt);
            return dt;
        }

        public int SelectDistinctCount(DataTable sourceTable, string fieldName)
        {
            return SelectDistinct(fieldName, sourceTable, fieldName).Rows.Count;
        }
    }
}
